package cn.wzvtc.demo.service;

import cn.wzvtc.demo.model.entity.FormTplEntity;
import cn.wzvtc.demo.model.entity.UserFormComponent;
import cn.wzvtc.demo.model.entity.UserFormEntity;
import cn.wzvtc.demo.model.vo.UserFormAnalyzeVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @description: 用户表单数据分析服务类
 * @author: Rex
 * @create: 2021-07-10 19:06
 */
@Service
public class UserFormAnalyzeService {
  @Autowired
  private MongoTemplate mongoTemplate;

  public UserFormAnalyzeVO returnValue(String formId, String componentId) {
    UserFormAnalyzeVO formResultEntity = new UserFormAnalyzeVO();
    Query query = new Query(Criteria.where("form_id").is(formId));
    List<UserFormEntity> userFormEntities = mongoTemplate.find(query, UserFormEntity.class);

    Map component = getComponent(formId, componentId);
    formResultEntity.setComponentId(componentId);
    formResultEntity.setFormId(formId);
    formResultEntity.setType((String) component.get("type"));
    formResultEntity.setTitle((String) component.get("title"));

    List<Map<String, String>> list = new ArrayList<>();
    userFormEntities.forEach(userForm -> {
      List<UserFormComponent> components = userForm.getComponents();
      components.forEach(userComponentDetail -> {
        if (userComponentDetail.getId().equals(componentId)) {
          list.add(userComponentDetail.getResults());
        }
      });
    });
    formResultEntity.setResults(list);
    System.out.println(formResultEntity);
    return formResultEntity;
  }

  private Map getComponent(String formId, String componentId){
    Aggregation agg = Aggregation.newAggregation(
            Aggregation.unwind("$components"),
            Aggregation.match(Criteria.where("_id").is(formId).and("components._id").is(componentId)),
            Aggregation.project("components").andExclude("_id")

    );
    AggregationResults<Map> res = mongoTemplate.aggregate(agg, FormTplEntity.class, Map.class);

    System.out.println(res.getMappedResults().get(0));
    return (Map) res.getMappedResults().get(0).get("components");
  }
}
